package com.example.lab04.controller;


import com.example.lab04.entity.User;
import com.example.lab04.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("user")
public class UserController extends BaseController {
   private final UserService userService;

   public UserController(UserService userService) {
      this.userService = userService;
   }

   @GetMapping ("queryAll")
   @ResponseBody
   public List<User> queryAll(){
      return userService.queryAll();
   }
   @PostMapping("create")
   @ResponseBody
   private boolean create(@RequestPart MultipartFile file, @RequestPart User user) throws IOException {

      System.out.println(user);
      // 保存上传的头像文件
      File directory = new File(application.getRealPath("/avatar")); // 上传文件存放的位置
      if (!directory.exists()) {
         System.out.println(directory.mkdirs());
      }
      String extension = StringUtils.getFilenameExtension(file.getOriginalFilename()); // 扩展名  png, jpg, ...
      String filename = UUID.randomUUID() + "." + extension; // 重定义唯一文件名
      file.transferTo(new File(directory, filename)); // 保存文件

      user.setAvatar(filename);
      userService.create(user);

      return true;
   }

   @PostMapping("queryByAccountAndPassword")
   @ResponseBody
   private User queryByAccountAndPassword(@RequestBody Map<String, String> map) {
      // todo
      return userService.queryOne("queryByAccountAndPassword", map);
   }
}




